package com.ljt.aidltestdemo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.ljt.aidlmodule.IMyAidlInterface;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView tvModule;
    ServiceConnection connection;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvModule = findViewById(R.id.tvModule);
        tvModule.setOnClickListener(this);
        initData();
    }

    private void initData() {
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d("TAG", "服务绑定成功");
                IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
                try {
                    tvModule.setText(iMyAidlInterface.getTestStr());
                } catch (RemoteException e) {
                    e.printStackTrace();
                    Log.e("TAG", "AIDL赋值异常-->" + e.getMessage());
                }

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d("TAG", "服务断开-->" + name.getPackageName());
            }
        };

        intent = new Intent();
        intent.setAction("com.ljt.yourxxaction");
        intent.setPackage("com.ljt.aidlmodule");
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvModule) {
            bindService(intent, connection, BIND_AUTO_CREATE);
        }
    }
}